/**
 * 
 */
package com.training.admin.web.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.demo2do.core.entity.result.HttpResult;
import com.training.admin.Constants;
import com.training.admin.entity.principal.Principal;
import com.training.admin.service.PrincipalService;


/**
 * @author Downpour
 */
@Controller
public class AuthenticationController {

    private static final Logger logger = LoggerFactory.getLogger(AuthenticationController.class);
    
    private static final String USER_KEY = Constants.USER_KEY;
    
    @Autowired
    private PrincipalService principalService;

    /**
     * Session invalid redirect
     * 
     * @param redirectAttributes
     * @return
     */
    @RequestMapping("/timeout")
    public String timeout(RedirectAttributes redirectAttributes) {

        logger.info("Session timeout ... The system will redirect to login page");
        
        // add a flag into session to display on login page
        redirectAttributes.addFlashAttribute("timeoutErrorMessage", "security.authentication.timeout");
        
        return "redirect:/login";
    }

    /**
     * @param request
     * @param httpSession
     * @param timeoutErrorMessage
     * @return
     */
    @RequestMapping(value = { "/", "/login" })
    public String login(HttpServletRequest request, HttpSession httpSession, @ModelAttribute("timeoutErrorMessage") String timeoutErrorMessage) {

        // Trying to get AuthenticationException from HttpSession
        AuthenticationException authenticationException = (AuthenticationException) httpSession.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        
        // when authentication exception is found, setting up error message to display
        if (authenticationException != null) {

            if (logger.isErrorEnabled()) {
                logger.error("Authentication process exception: " + authenticationException.getMessage());
            }            
            
            request.setAttribute("errorMessage", "security.authentication.fail");
            
            if (authenticationException.getCause() instanceof LockedException) {
                request.setAttribute("errorMessage", authenticationException.getMessage());
            }
            
            // remove AuthenticationException from httpSession
            httpSession.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
            
            return "login";
        }

        return "login";
    }
    
    /**
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/auto-login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public  @ResponseBody HttpResult onAutoLogin(HttpServletRequest request) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            Cookie usernameCookie = org.springframework.web.util.WebUtils.getCookie(request, USER_KEY);
            if (usernameCookie == null) {
                return httpResult.fail("500").message("不存在任何cookie");
            }
            
            Principal principal = principalService.loadByName(usernameCookie.getValue());
            logger.info("get cookie [{}]", usernameCookie.getValue());
            if(principal == null) {
                return httpResult.fail("500").message("不存在任何后台用户");
            }
            
            return httpResult.success().data("name", principal.getName()).data("password", principal.getOriginPassword()).message("获取自动登录信息成功");
            
        } catch (Exception e) {
            logger.error("auto login error", e);
            return httpResult.fail("500").message("自动登录异常");
        }
    }

    /**
     * Execute post login process
     * 
     * @param principal
     * @return
     */
    @RequestMapping("/post-login")
    public String postLogin() {
        return "redirect:/project-data";
    }

}
